package upicgame.cart.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import upicgame.cart.dao.CartDao;
import upicgame.entity.CartItem;
import upicgame.entity.Game;
import upicgame.entity.Library;
import upicgame.entity.User;
import upicgame.gamelibrary.dao.LibraryDao;

@Service
public class AccountService {
	@Autowired
	private CartDao cd;
	@Autowired
	private CartService cs;
	@Autowired
	private LibraryDao ld;

	public String singleAccount(Integer uid, Integer gid) {
		User user = cd.accountFindUserById(uid);
		Game game = null;
		boolean account = false;
		// 判断结算状态
		for (CartItem temp : user.getCart()) {
			game = temp.getGame();
			if (game.getId() == gid) {
				account = temp.isAccount();
			}
		}
		double result = user.getMoney() - game.getDiscountprice();
		if (account && result >= 0) {
			// 更新钱
			user.setMoney(result);
			// 添加游戏进入库
			ld.addGameInLibrary(new Library(user, game));
			// 删除对应购物项
			cs.delCartItem(uid, gid);
			return "SUCCESS";
		} else {
			return "余额不足,或已拥有";
		}

	}

	public String allAccount(Integer uid) {
		User user = cd.accountFindUserById(uid);
		double price = 0;
		for (CartItem temp : user.getCart()) {
			if (temp.isAccount()) {
				price += temp.getGame().getDiscountprice();
			}
		}
		double result = user.getMoney() - price;
		if (result >= 0) {
			// 更新钱
			user.setMoney(result);
			for (CartItem item : user.getCart()) {
				if (item.isAccount()) {
					// 添加游戏进入库
					ld.addGameInLibrary(new Library(user, item.getGame()));
					// 从购物车中删除
					cs.delCartItem(uid, item.getGame().getId());
				}
			}
			return "SUCCESS";
		} else {
			return "余额不足";
		}

	}

}
